package wwiii;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;

@PersistenceCapable(detachable = "true")
public class AreaMap {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;
	public Key getKey() { return key; }

	@Persistent
	private int width;
	public int getWidth() { return width; }

	@Persistent
	private int height;
	public int getHeight() { return height; }

	@Persistent
	private int areaSize;
	public int getAreaSize() { return areaSize; }

	@Persistent(defaultFetchGroup = "true")
	@Element(dependent = "true")
	private List<Area> areas = new ArrayList<Area>();

	public Collection<Area> getAreas() {
		return new ArrayList<Area>(areas);
	}
	public int getAreaCount() {
		return areas.size();
	}
	public Area getArea(int n) {
		return areas.get(n);
	}
	public Area getArea(String name) {
		if (areas != null) for (Area area : areas) {
			if (area.getName().equals(name)) return area;
		}

		return null;
	}
	public void addArea(Area area) {
		areas.add(area);
	}

	public AreaMap(int width, int height, int areaSize) {
		this.width    = width;
		this.height   = height;
		this.areaSize = areaSize;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof AreaMap) {
			return equals((AreaMap) obj);
		}

		return false;
	}
	private boolean equals(AreaMap that) {
		if (key == null && that.key == null) return true;

		return key.equals(that.key);
	}

	@Override
	public int hashCode() {
		return key.hashCode();
	}

	@Override
	public String toString() {
		return "[AreaMap "+ areas +"]";
	}
}
